package com.example.authority.controller;
import com.alibaba.excel.EasyExcel;
import cn.hutool.core.util.StrUtil;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.excel.read.listener.PageReadListener;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.authority.common.Result;
import com.example.authority.entity.Collect;
import com.example.authority.service.CollectService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletResponse;

import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.net.URLEncoder;
import java.util.Arrays;
import java.util.List;


import com.example.authority.service.UserService;
import com.example.authority.entity.User ;
import com.example.authority.service.SeedcategoryService;
import com.example.authority.entity.Seedcategory ;
import com.example.authority.service.SeekService;
import com.example.authority.entity.Seek;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;




/**
 * @program:   
 * @ClassName:SeekController
 * @description: SeekController前端控制器
 *       
 * @Version 3.0
 **/
@Tag(name = "种子管理 前端控制器")
    @RestController
@RequestMapping("/seek")
    public class SeekController {

@Resource
private SeekService seekService;
@Resource
private UserService userService;
    @Resource
    private CollectService collectService;
@Resource
private SeedcategoryService seedcategoryService;

/**
 * 新增
 * @param seek
 * @return
 */
@Operation(summary = "新增")
@PostMapping
@Transactional
public Result save(@RequestBody Seek seek){
    seek.setIsdiscount(0);
    // 获取用户并更新下载次数
    User user = userService.getById(seek.getUserid());
    if (user != null) {
        user.setUpdateNum(user.getUpdateNum() + 1);
        // 更新经验值
        int newExperience = user.getExperience() + 1;
        if (newExperience > 6) {
            user.setExperience(0);
            user.setGrade(user.getGrade() + 1);
        } else {
            user.setExperience(newExperience);
        }
        userService.updateById(user);
    }
    return Result.success(seekService.save(seek));
}
/**
* 修改
*
* @param seek
* @return
*/
@Operation(summary = "修改")
@PutMapping("/{id}")
public Result update(@PathVariable Long id,@RequestBody Seek seek) {
        return Result.success(seekService.updateById(seek));
        }

/**
 * 查询所有Seek
 * @return
 */
@Operation(summary = "查询所有Seek")
@GetMapping
public Result findAll(){
        return Result.success(seekService.list());
        }
/**
  * 获取单个
  * @param id
  * @return
  */
@Operation(summary = "获取单个")
@GetMapping("/{id}")
public Result findOne(@PathVariable Integer id){
    Seek seek = seekService.getById(id);
    if (seek != null) {
        // 获取分类信息
        Seedcategory seedcategory = seedcategoryService.getById(seek.getCategoryid());
        if (seedcategory != null) {
            seek.setSeedcategory(seedcategory);
        }
        // 获取用户信息
        User user = userService.getById(seek.getUserid());
        if (user != null) {
            seek.setUser(user);
        }
        seek.setIsCollect(collectService.list(
                new LambdaQueryWrapper<Collect>().eq(Collect::getUid,userService.getUserInfo().getId()).eq(Collect::getSid,seek.getId())
        ).size()>0);
    }
    return Result.success(seek);
}
/**
 * 分页显示
 * @param
 * @param pageNum
 * @param pageSize
 * @return
 */
@Operation(summary = "分页显示")
@GetMapping("/page")
public Result findPage(
        @RequestParam(defaultValue = "") Long userid,
        @RequestParam(defaultValue = "") String seekContent,
        @RequestParam(defaultValue = "") Integer isCheck,
        @RequestParam(defaultValue = "") String seedname,
        @RequestParam(defaultValue = "") Long categoryid,
        @RequestParam(defaultValue = "") Integer downloadGrade,
@RequestParam(defaultValue = "1") Integer pageNum,
@RequestParam(defaultValue = "10") Integer pageSize){

        LambdaQueryWrapper<Seek>queryWrapper=new LambdaQueryWrapper();
        if (userid!=null&&userid!=0) {
            // name 不为空且不是空字符串的处理逻辑
            queryWrapper.eq(Seek::getUserid,userid);
        }
        if (StrUtil.isNotEmpty(seekContent)) {
            // name 不为空且不是空字符串的处理逻辑
            queryWrapper.like(Seek::getSeekContent,seekContent);
        }
        if (isCheck!=null&&isCheck!=0) {
            // name 不为空且不是空字符串的处理逻辑
            queryWrapper.eq(Seek::getIsCheck,isCheck);
        }
        if (StrUtil.isNotEmpty(seedname)) {
            // name 不为空且不是空字符串的处理逻辑
            queryWrapper.like(Seek::getSeedname,seedname);
        }
        if (categoryid!=null&&categoryid!=0) {
            // name 不为空且不是空字符串的处理逻辑
            queryWrapper.eq(Seek::getCategoryid,categoryid);
        }
        if (downloadGrade!=null&&downloadGrade!=0) {
            // name 不为空且不是空字符串的处理逻辑
            queryWrapper.eq(Seek::getDownloadGrade,downloadGrade);
        }

        queryWrapper.orderByDesc(Seek::getId);
        Page<Seek>page=seekService.page(new Page<>(pageNum,pageSize),queryWrapper);
        List<Seek > records = page.getRecords();
         for (Seek seek : records) {
                 User user = userService.getById(seek.getUserid());
                 if (ObjectUtil.isNotEmpty(user)){
                     seek.setUser(user);
                 }
                 Seedcategory seedcategory = seedcategoryService.getById(seek.getCategoryid());
                 if (ObjectUtil.isNotEmpty(seedcategory)){
                     seek.setSeedcategory(seedcategory);
                 }
         }
         page.setRecords(records);
         return Result.success(page);

        }
/**
* 单个删除
* @param id
* @return
*/
@Operation(summary = "单个删除")
@DeleteMapping("/{id}")
public Result delete(@PathVariable Integer id){
        return Result.success(seekService.removeById(id));
        }
/**
* 批量删除
* @param ids
* @return
*/
@Operation(summary = "批量删除")
@DeleteMapping("/batch/{ids}")
@Transactional
public Result deleteByIds(@PathVariable String[]ids){
        return Result.success(seekService.removeByIds(Arrays.asList(ids)));
        }

/**
 * 批量导出
 * 使用的技术为alibaba下面的easyexcel
 * 写数据
 *
 * @param ids
 * @return
 */
@Operation(summary = "批量导出")
@GetMapping("/batch/export/{ids}")
public void exportByIds(@PathVariable String[] ids, HttpServletResponse response) throws IOException {

        List<Seek> list = seekService.listByIds(Arrays.asList(ids));
        // 这里注意 有同学反应使用swagger 会导致各种问题，请直接用浏览器或者用postman
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("utf-8");
        // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
        String fileName = URLEncoder.encode("seek导出数据", "UTF-8").replaceAll("\\+", "%20");
        response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
        EasyExcel.write(response.getOutputStream(), Seek.class).sheet("sheel1").doWrite(list);

        }

/**
 * 批量导入
 * 使用的技术为alibaba下面的easyexcel
 * 读数据
 *
 * @param
 */
@Operation(summary = "批量导入")
@PostMapping("/batch/upload")
public Result writeExcel(MultipartFile file) throws IOException {
        EasyExcel.read(file.getInputStream(), Seek.class, new PageReadListener<Seek>(dataList -> {
        dataList.forEach(entity -> seekService.save(entity.toBuilder().id(null).build()));
        })).sheet().doRead();
        return Result.success();
        }
@GetMapping("/accessCheck")
public Result accessCheck(@RequestParam Long id) {
    Seek seek = seekService.getById(id);
    if (seek != null) {
        seek.setIsCheck(1);
        seekService.updateById(seek);
        return Result.success();
    }
    return Result.error("未找到该记录");
}
@GetMapping("/discount")
public Result discount(@RequestParam Long id, @RequestParam int grade) {
    Seek seek = seekService.getById(id);
    seek.setIsdiscount(1);
    if (seek != null) {
        seek.setDownloadGrade(grade);
        seekService.updateById(seek);
        return Result.success();
    }
    return Result.error("未找到该记录");
}



}